package com.cin.cma.client.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.cin.cma.client.service.ICallbackService;
import com.cin.cma.common.constant.MsgTypeConstant;
import com.cin.cma.common.model.SocketRequest;
import com.cin.cma.common.model.SocketResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class CallbackServiceImpl implements ICallbackService {
    /**
     * 回调发送
     *
     * @param socketRequest  业务入参
     * @param socketResponse 业务结果
     */
    @Override
    public void send(SocketRequest socketRequest, SocketResponse socketResponse) {
        try {
            if (StrUtil.isNotBlank(socketRequest.getMessageType()) && StrUtil.isNotBlank(socketRequest.getCallbackUrl()) &&
                    (socketRequest.getMessageType().equals(MsgTypeConstant.ASYNC) ||
                            socketRequest.getMessageType().equals(MsgTypeConstant.TOGETHER))) {
                String callbackBody = socketResponse.toString();
                ThreadUtil.execAsync(() -> {
                    for (int i = 1; i <= 10; i++) {
                        try {
                            String result = HttpRequest.post(socketRequest.getCallbackUrl()).body(callbackBody).execute().body();
                            if (!"success".equals(result)) {
                                throw new Exception(result);
                            }
                            break;
                        } catch (Exception e) {
                            log.error("回调结果异常,请求地址：{},请求参数：{}", socketRequest.getCallbackUrl(), callbackBody, e);
                            ThreadUtil.sleep(i * 10000);
                        }
                    }
                });
            }
        } catch (Exception e) {
            log.error("回调结果执行器异常,socketRequest={},socketResponse={}", socketRequest, socketResponse, e);
        }
    }
}
